<template>
  <div id="app">
    <router-view />
    <van-overlay :show="loading" class-name="loadingOverlay">
      <div class="loadingOverlayContainer">
        <van-loading size=".56rem" color="#1989fa" />
      </div>
    </van-overlay>
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import {
  basePrefix,
  getCookie,
  getStorageObj,
  formatAvatarList
} from "./js/utils";
import { mapMutations, mapState, mapActions } from "vuex";
import { TenonWebsocket } from "./js/websocket";
import qs from "qs";
import { post } from "./js/utils";
import { Dialog, Overlay, Loading, Toast } from "vant";
import HelpIcon from "@/components/HelpIcon";
import eruda from "eruda";
// eruda.init();
export default {
  name: "App",
  components: {
    Dialog,
    HelpIcon,
    [Overlay.name]: Overlay,
    [Loading.name]: Loading
  },
  async created() {
    //测试用
    //外部浏览器跳过
    let viewer = window.navigator.userAgent.toLowerCase();
    if (viewer.match(/MicroMessenger/i) == "micromessenger") {
      //微信浏览器
      let jsApiTicket = await post("/mp/getJsapiConfig", {
        url: encodeURI(window.location.href)
      });

      //1、判断是否没有授权，没授权则重定向授权
      let redirect = await this.redirectOrNot(jsApiTicket);
      //2、若是通过用户，则获取用户信息
      if (redirect) {
        const resQuery = qs.parse(
          window.location.href.split("?")[1].split("#")[0]
        );
        let user = await post("/mp/oauth2getAccessToken", {
          code: resQuery.code
        });
        console.log("user", user);
        if (user != null) {
          this.loadUser(user);
        } else {
          // this.setUserId(this.$store.state.userInfo.openId);
          console.log("userId", this.$store.state.userId);
          if (this.$store.state.userId) {
          } else {
            let auth = await this.redirectAuth(jsApiTicket);
            if (auth) {
              return;
            }
          }
        }
        //3、url添加调试代码
        this.debug();
        //4、添加业务
        // await this.doBusiness(resQuery, jsApiTicket);
        //分享
        wx.config({
          debug: false,
          beta: true,
          appId: jsApiTicket.appId,
          timestamp: jsApiTicket.timestamp,
          nonceStr: jsApiTicket.nonceStr,
          signature: jsApiTicket.signature,
          jsApiList: [
            "checkJsApi",
            "updateAppMessageShareData",
            "onMenuShareAppMessage",
            "openLocation"
          ]
        });
        let self = this;
        wx.ready(function() {
          self.setAppData({
            resQuery,
            jsApiTicket
          });
        });
      }
    }
  },
  computed: {
    ...mapState(["userId", "subscribe", "loading", "userInfo", "sharePagam"])
  },
  mounted() {
    console.log(
      "width,heigth,dpr",
      document.documentElement.clientWidth,
      document.documentElement.clientHeight,
      window.devicePixelRatio
    );
  },
  methods: {
    ...mapMutations({
      setJsapiTicket: "setJsapiTicket",
      setUserId: "setUserId",
      setSubscribe: "setSubscribe",
      setShareParams: "setShareParams",
      setActivityMsg: "setActivityMsg",
      setUserInfo: "setUserInfo",
      setSupInfoMy: "activity/setSupInfoMy",
      setAvListMy: "activity/setAvListMy",
      pageReady: "activity/pageReady",
      setAvList: "activity/setAvList",
      setSupInfo: "activity/setSupInfo",
      setAppData: "setAppData",
      setStaffInfo: "setStaffInfo"
    }),
    ...mapActions({
      getSupInfo: "activity/getSupInfo",
      getUserSupId: "activity/getUserSupId"
    }),
    redirectOrNot(jsApiTicket) {
      return new Promise((resolve, reject) => {
        const baseUrl = window.location.href;
        const resQuery = qs.parse(
          window.location.href.split("?")[1].split("#")[0]
        );
        //重定向服务器
        if (
          typeof resQuery == "undefined" ||
          typeof resQuery.code == "undefined" ||
          resQuery.code == null
        ) {
          console.log("重定向");
          const redirectUrl = encodeURIComponent(baseUrl);
          const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${jsApiTicket.appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
          window.location.href = dst;
          resolve(0);
        }
        resolve(1);
      });
    },
    redirectAuth(jsApiTicket) {
      return new Promise((resolve, reject) => {
        const baseUrl = window.location.href;
        const resQuery = qs.parse(
          window.location.href.split("?")[1].split("#")[0]
        );
        let regStrArr = [];
        if (resQuery.code) {
          let str = qs.stringify({
            code: resQuery.code
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr})`);
        }
        if (resQuery.state) {
          let str = qs.stringify({
            state: resQuery.state
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr})`);
        }
        if (resQuery.from) {
          let str = qs.stringify({
            from: resQuery.from
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr})`);
        }
        let regStr = regStrArr.join("|");

        let reg3 = new RegExp(regStr, "g");
        let url1 = baseUrl.replace(reg3, "");
        // url1 = url1.replace(reg2, "");
        const redirectUrl = encodeURIComponent(url1);
        const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${jsApiTicket.appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
        window.location.href = dst;
        resolve(1);
      });
    },
    loadUser(user) {
      this.setUserInfo(user);
    },
    debug: function() {
      let { debug } = qs.parse(
        window.location.href.split("#")[0].split("?")[1]
      );
      if (debug) {
        localStorage.clear();
        sessionStorage.clear();
      }
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* text-align: center; */
  color: #2c3e50;
}
</style>
